package com.xzcs.directive.blog;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzcs.mapper.blog.content.ContentMapper;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.freemarker.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 博客内容
 * @author: chang
 * @date: 2017/6/16
 */
@Component("fl_blog_content_list")
public class ContentListDirective implements TemplateDirectiveModel {

	public Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ContentMapper contentMapper;

	public void execute(Environment env, Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
		String status = DirectiveUtils.getString("status", params);//大于的level
		String categoryId = DirectiveUtils.getString("categoryId", params);
		String pageNum = DirectiveUtils.getString("pageNum", params);
		String pageSize = DirectiveUtils.getString("pageSize", params);
		pageNum = pageNum.equals("") ? "1" : pageNum;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", status);
		map.put("categoryId", categoryId);
		PageHelper.startPage(StringUtils.toInt(pageNum), StringUtils.toInt(pageSize));
		List<Map<String, Object>> list = contentMapper.findContents(map);
		PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
		env.setVariable(DirectiveUtils.OUT_BEAN, DirectiveUtils.getDefaultObjectWrapper().wrap(page));

		body.render(env.getOut());
	}
}
